const express = require("express");
const router = express.Router();
const UsersModel = require("../../db/modules/users");
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const {SECRET} = require('../../config/config')
router.post("/login", function (req, res) {
  UsersModel.findOne({userName:req.body.username}).then((result) => {
    if (!result) {
      return res.json({
        code: 400,
        msg: '账号不存在，请先注册',
        data: null,
      });
    }
    UsersModel.findOne({password:md5(req.body.password)}).then((result) => {
      if (!result) {
        return res.json({
          code: 400,
          msg: '密码错误',
          data: null,
        });
      }
      const token = jwt.sign({userName:result.userName,_id:result._id},SECRET,{
        expiresIn: 60 * 60 * 24 * 7
      })
      res.json({
        code: 0,
        msg: '登录成功',
        data: token,
      });
    })
    .catch((error) => {
      res.json({
        code: 500,
        msg: "操作失败",
        data: error,
      });
    });
  })
  .catch((error) => {
    res.json({
      code: 500,
      msg: "操作失败",
      data: error,
    });
  });
});

router.post("/logout", function (req, res) {
  req.session.destroy(() => {
    res.json({
      code: 0,
      msg: '退出成功',
      data: null,
    });
  })
});
module.exports = router;
